package com.atguigu.day02;

/**
 * @ClassName CountDownLatchDemo
 * @Description 此类描述:
 * @Author dangchen
 * @DateTime 2022-09-07 18:53
 * @Version 1.0
 */

import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch主要有两个方法,当一个或多个线程调用await方法时,这些线程
 * 会阻塞,其他线程调用CountDown方法会将计数器减1(调用countDown方法的线程不会阻塞),当计数器的值变为0时,因await方法阻塞的线程会被唤醒,继续执行
 */
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for (int i = 1; i <= 6 ; i++) {//如果count设置为6,但是循环10次,结果可能达不到预期,锁门后可能还有人离开教室;但是如果不设置for循环,则当计数器的值变为0时,因await方法阻塞的main线程就会被唤醒
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "\t 离开教室了...");
                countDownLatch.countDown();
            },String.valueOf(i)).start();
        }
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName() + "\t 班长锁门了...");
    }

}
